package com.zxw.hotel.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zxw.hotel.common.Pageinfo;
import com.zxw.hotel.dao.RoomDao;
import com.zxw.hotel.model.Over;
import com.zxw.hotel.model.Room;
import com.zxw.hotel.model.extend.RoomExtend;
import com.zxw.hotel.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {
    private RoomDao roomDao;

    @Autowired
    public void setRoomDao(RoomDao roomDao) {
        this.roomDao = roomDao;
    }

    @Override
    public List<Room> getAll(Pageinfo pageinfo, RoomExtend roomExtend) {
        roomDao.setstatus0();
        //通过reserve表中的roomid查询birthFrom 和 birthTo
        List<Over> over = roomDao.selectover();
        if (!over.isEmpty()) {
            for (Over o : over) {
                LocalDateTime now = LocalDateTime.now();
                if (!now.isBefore(o.getBirthFrom().atStartOfDay()) && !now.isAfter(o.getBirthTo().atStartOfDay())) {
                    //如果当前时间在birthFrom 和 birthTo之间则将房间状态设为1
                    roomDao.updateOvery(o.getRoomId());
                } else {
                    //如果当前时间不在birthFrom 和 birthTo之间则将房间状态设为0
                    roomDao.updateOverf(o.getRoomId());
                }
            }


        }

        try (Page<?> __ = PageHelper.startPage(pageinfo.getPageNo(), pageinfo.getPageSize())) {
            return roomDao.getAll(roomExtend);
        }
    }

    @Override
    public int delete(Integer[] ids) {
        return roomDao.delete(ids);
    }

    @Override
    public int add(RoomExtend roomExtend) {
        if (roomExtend.getRoomId() == null || roomExtend.getRoomId().isEmpty() || roomExtend.getRoomName() == null
                || roomExtend.getRoomName().isEmpty() || roomExtend.getRoomStatus() == null ||
                roomExtend.getRoomStatus().isEmpty() ||roomExtend.getFacilityName()==null|| roomExtend.getFacilityName().isEmpty()) {
            return 0;
        }
        try {
            int add = roomDao.add(roomExtend);
            return add;
        } catch (Exception e) {
            return 0;
        }

    }

    @Override
    public int update(RoomExtend roomExtend) {
        if (roomExtend.getRoomId() == null || roomExtend.getRoomId().isEmpty() ||
                roomExtend.getRoomName() == null || roomExtend.getRoomName().isEmpty() ||
                roomExtend.getRoomStatus() == null || roomExtend.getRoomStatus().isEmpty() ||roomExtend.getFacilityName()==null||
                roomExtend.getFacilityName().isEmpty()) {
            return 0;
        }
        try {
            int update = roomDao.update(roomExtend);
            return update;
        } catch (Exception e) {
            return 0;
        }

    }


}
